package com.it.word_count;


import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.tuple.Tuple2;


/**
 * 基于批处理实现的word count.
 * FlatMapOperator/AggregateOperator最终都是使用DataSet API.
 *
 * @author code1997
 */
public class BatchWordCount {
    public static void main(String[] args) throws Exception {
        //创建执行环境
        ExecutionEnvironment executionEnvironment = ExecutionEnvironment.getExecutionEnvironment();
        String filePath = "data/word_count/batch/words.txt";
        DataSource<String> dataSource = executionEnvironment.readTextFile(filePath);
        //如果使用lambda表达式会出现泛型擦除, 需要使用returns来指定返回的类型.
        FlatMapOperator<String, Tuple2<String, Long>> tupleWords = dataSource.flatMap((FlatMapFunction<String, Tuple2<String, Long>>) (s, collector) -> {
            String[] words = s.split(" ");
            for (String word : words) {
                collector.collect(Tuple2.of(word, 1L));
            }
        }).returns(Types.TUPLE(Types.STRING, Types.LONG));
        AggregateOperator<Tuple2<String, Long>> wordCountResult = tupleWords.groupBy(0).sum(1);
        wordCountResult.print();

    }
}
